package com.company.modules.project.controller;

import com.alibaba.fastjson.JSONObject;
import com.company.common.utils.R;
import com.company.modules.project.form.ModifyPasswordForm;
import com.company.modules.project.service.CompanyService;
import com.company.modules.project.service.EmployeeService;
import com.company.modules.project.service.ForgetPasswordService;
import com.company.modules.project.service.LoginAuthorService;
import com.company.modules.project.entity.Employee;
import com.company.modules.project.entity.LoginAuthor;
import com.company.modules.project.util.HostHolder;
import com.company.modules.project.util.HrmUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : Real
 * @date : 2022/1/27 14:39
 * @description :
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private LoginAuthorService loginAuthorService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private ForgetPasswordService forgetPasswordService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HostHolder hostHolder;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public R login(@RequestBody JSONObject json) {
        // TODO : 改变返回结果
        String username = json.getString("username");
        String password = json.getString("password");
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            map.put("data", "参数为空");

        }
        LoginAuthor loginAccount = loginAuthorService.findLoginAuthorByLoginAccount(username);
        if (loginAccount == null) {
            map.put("data", "不存在登录账号");

        }
        // 登录验证的方式： md5(password + salt) == database.password
        String accountPassword = loginAccount.getPassword();
        if (accountPassword == null) {

        }
        if (accountPassword.equals(HrmUtil.md5(password + loginAccount.getSalt()))) {
            // 登录的用户可能为 员工/部门管理员/公司管理员：均可以在 Employee 中找到
            // 超级管理员登录的是另一个 界面 / 接口
            Integer userId = loginAccount.getUserId();
            Employee employee = employeeService.findEmployeeById(userId);
            hostHolder.setEmployee(employee);
            // 存储对象完毕之后，封装对象数据

        } else {

        }
        return R.ok();
    }

    @RequestMapping(path = "/modify-password", method = RequestMethod.POST)
    public R modifyPassword(@RequestBody ModifyPasswordForm form) {
        // 需要修改所有的密码，重置 Salt 值
        String account = form.getAccount();
        String originalPassword = form.getOriginalPassword();
        String newPassword = form.getNewPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(newPassword)) {
            return R.error("您的输入有误，请重新输入");
        }
        LoginAuthor loginAccount = loginAuthorService.findLoginAuthorByLoginAccount(account);
        if (loginAccount == null || !loginAccount.getPassword().equals(originalPassword)) {
            return R.error("您的输入有误，请重新输入");
        }
        // 目标账户存在并且原始密码和输入密码相符，获得修改资格
        String salt = HrmUtil.generateSalt();
        String password = HrmUtil.md5(newPassword + salt);
        // DAO 已经进行了封装，直接操作可以修改所有的密码
        int i = loginAuthorService.modifyLoginAuthorPassword(loginAccount.getUserId(), password, salt);
        if (i >= 1) {
            return R.ok().put("data", "修改成功，请重新登录");
        } else {
            return R.error("修改失败，请重新尝试");
        }
    }


}
